﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
using System.IO;

namespace diplom
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public Boolean Saved = true;
        public double Skv()
        {
            int count;
            double sum = 0;
            count = richTextBox1.Lines.Length - 1;
            for (int i = 0; i <= count; i++)
            {
                sum = sum + Math.Pow(Convert.ToDouble(richTextBox1.Lines[i]) - SerAr(), 2);
            }
            return Math.Sqrt(sum / (count));
        }

        public double Skvwithout(int rem)
        {
            int count;
            double sum = 0;
            count = richTextBox1.Lines.Length - 1;
            for (int i = 0; i <= count; i++)
            {
                if (i!=rem)
                {
                    sum = sum + Math.Pow(Convert.ToDouble(richTextBox1.Lines[i]) - SerAr(), 2);
                }   
            }
            return Math.Round(Math.Sqrt(sum / (count-1)),3);
        }

        public double SerAr()
        {
            int count;
            double sum = 0;
            count = richTextBox1.Lines.Length - 1;
            for (int i = 0; i <= count; i++)
            {
                sum = sum + Convert.ToDouble(richTextBox1.Lines[i]);
            }
            return Math.Round(sum / (count + 1),3);
        }

        public double SerArwithout(int rem)
        {
            int count;
            double sum = 0;
            count = richTextBox1.Lines.Length - 1;
            for (int i = 0; i <= count; i++)
            {
                if (i!=rem)
                {
                    sum = sum + Convert.ToDouble(richTextBox1.Lines[i]);
                }
            }
            return sum / (count);
        }

        public void Romanov()
        {
            List<double> tp = new List<double>();
            try
            {
                using (StreamReader sr = new StreamReader("tp.txt"))
                {
                    String line;

                    while ((line = sr.ReadLine()) != null)
                    {
                        tp.Add(Convert.ToDouble(line));
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("The file could not be read:");
                MessageBox.Show(e.Message);
            }
            int n = richTextBox1.Lines.Length - 1;
            List<string> temporary = new List<string>();
            for (int i = 0; i <= n; i++)
            {
                if ((Convert.ToDouble(richTextBox1.Lines[i]) - SerArwithout(i)) < (tp[n] * Skvwithout(i)))
                {
                    temporary.Add(richTextBox1.Lines[i]);
                }
                else
                {
                    richTextBox2.Text += richTextBox1.Lines[i];
                }
            }
            richTextBox1.Clear();
            for (int i = 0; i < temporary.Count(); i++)
            {
                if ((i+1)!=temporary.Count())
                {
                    richTextBox1.Text += temporary[i] + "\n";
                }
                else
                {
                    richTextBox1.Text += temporary[i];
                }  
            }
        }

        public void remove()
        {
            progressBar1.Visible = true;
            progressBar1.Value = 10;
            double skvt = 3 * Skv(), sa = SerAr();
            sa = Math.Round(sa, 3);
            List<double> tmp = new List<double>();
            int c = 0;
            progressBar1.Value = 20;
            for (int i = 0; i <= richTextBox1.Lines.Length-1 ; i++)
            {
                if ((Convert.ToDouble(richTextBox1.Lines[i]) - sa) >= skvt)
                {
                    richTextBox2.Text += richTextBox1.Lines[i] + "\n";
                }
                else
                {
                    tmp.Add(Convert.ToDouble(richTextBox1.Lines[i]));
                    c++;
                }
            }
            progressBar1.Value = 40;
            int count_tmp = c - 1;
            double tmp_value;
            Boolean t = true;
            while (t)
            {
                t = false;
                for (int j = 0; j < tmp.Count()-1 ; j++)
                {
                    if (tmp[j] > tmp[j + 1])
                    {
                        tmp_value = tmp[j];
                        tmp[j] = tmp[j + 1];
                        tmp[j + 1] = tmp_value;
                        t = true;
                    }
                }
            }
            progressBar1.Value = 60;
            richTextBox1.Clear();
            for (int i = 0; i <= count_tmp; i++)
            {
                if (i != count_tmp)
                {
                    richTextBox1.Text += tmp[i].ToString() + "\n";
                }
                else
                {
                    richTextBox1.Text += tmp[i].ToString();
                }
            }
            progressBar1.Value = 80;
            Romanov();
            progressBar1.Value = 100;
            progressBar1.Visible = false;
        }

        public void ifNormal()
        {
            double n = richTextBox1.Lines.Length;
            double sigmaX = Math.Round(Skv(), 3) / Math.Sqrt(n);
            sigmaX = Math.Round(sigmaX, 3);
            richTextBox5.Text += "\nСКВ значення СА = " + sigmaX.ToString();
            double xmax = Convert.ToDouble(richTextBox1.Lines[richTextBox1.Lines.Length-1]);
            double z = (xmax - Math.Round(SerAr(), 3)) / Math.Round(Skv(), 3);
            double deltaX = z*sigmaX;
            deltaX = Math.Round(deltaX,3);
            richTextBox5.Text += "\nПохибка = " + deltaX.ToString();
            double ser = Math.Round(SerAr(),3);
            richTextBox7.Text += "Результат вимірювання    ";
            richTextBox7.Text += "x = "+ser.ToString() +" +/- "+deltaX.ToString();
        }

        public void ifNotNormal()
        {
            double sigmaX, summa=0, ser = Math.Round(SerAr(),3),
                n=richTextBox1.Lines.Length;
            foreach (var val in richTextBox1.Lines)
            {
                summa += (Convert.ToDouble(val) * Convert.ToDouble(val)) - (ser * ser);
            }
            
            sigmaX = Math.Round((Math.Sqrt(summa)) / n,3);
            richTextBox5.Text += "\nСКВ значення СА = " + sigmaX.ToString();
            double psx = 0.95;
            if (psx >= (1 - Math.Pow((sigmaX / Convert.ToDouble(textBox8.Text)), 2)))
            {
                richTextBox7.Text += "Результат вимірювання    ";
                richTextBox7.Text += "x = " + ser.ToString() + " +/- " + textBox8.Text;
            }
        }

        public double pirson()
        {
            progressBar1.Visible = true;
            progressBar1.Value = 10;
            label13.Text = "hi^2";
            label14.Text = "z-Ф(z)";
            double r = (Convert.ToDouble(richTextBox1.Lines[richTextBox1.Lines.Length - 1])) - Convert.ToDouble(richTextBox1.Lines[0]);
            r = Math.Round(r, 3);
            double   interval = r / 5;
            double rmax = (1.25 * Math.Pow(richTextBox1.Lines.Length, 0.4));
            int range = (Convert.ToInt16(rmax) - 3);
            double[] x = new double[range + 5];
            int[] m = new int[range + 5];
            interval = Math.Round(interval, 4);
            richTextBox3.Clear();
            progressBar1.Value = 20;
            try
            {
                using (StreamReader sr = new StreamReader("laplas.txt"))
                {
                    String line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        richTextBox3.Text += line + "\n";
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("The file could not be read:");
                MessageBox.Show(e.Message);
            }
            progressBar1.Value = 30;
            Double[] xin = new Double[range + 5];
            Double[] xiv = new Double[range + 5];
            int f = 0, d = 0;
            x[f] = Convert.ToDouble(richTextBox1.Lines[0]) + interval;
            x[f] = Math.Round(x[f], 3);
            xin[0] = Convert.ToDouble(richTextBox1.Lines[0]);
            Boolean bxin = false;
            Boolean min = true;  
            for (int i = 0; i <= richTextBox1.Lines.Length-1; i++)
            {
                if (Convert.ToDouble(richTextBox1.Lines[i]) <= x[f])
                {
                    if (min)
                    {
                        if (bxin)
                        {
                            xin[d] = x[f-1];
                        }
                        bxin = true;
                        min = false;
                    }
                    m[d]++;
                }
                if (Convert.ToDouble(richTextBox1.Lines[i]) > x[f])
                {
                    x[f + 1] = Math.Round(x[f] + interval,3);
                    if (m[d] != 0)
                    {
                        f++;
                    }
                    xiv[d] = x[f-1];
                    d++;
                    min = true;
                    if(i == richTextBox1.Lines.Length-1)
                    {
                        xiv[d] = Convert.ToDouble(richTextBox1.Lines[i]);
                    }
                    i--;
                }
                if (i == richTextBox1.Lines.Length - 1) xiv[d] = Convert.ToDouble(richTextBox1.Lines[i]);
            }
            progressBar1.Value = 40;
            int[] mnew = new int[m.Length - 1];
            for (int j = 0; j <= m.Length - 1; j++)
            {
                if ((m[j] < 5) && (m[j + 1] != 0))
                {
                    m[j + 1] += m[j];
                    m[j] = 0;
                    xin[j + 1] = xin[j];
                    xin[j] = 0;
                    xiv[j] = 0;
                }
                if ((m[j] < 5) && (m[j + 1] == 0) && (j != 0))
                {
                    m[j - 1] += m[j];
                    m[j] = 0;
                    xiv[j - 1] = xiv[j];
                    xiv[j] = 0;
                    xin[j] = 0;

                }
                if ((m[j + 1] == 0) && (m[j + 2] == 0)) break;
            }
            double[] px = new double[m.Length];
            int p = 0;
            foreach (int val in m)
            {
                if (val != 0)
                {
                    px[p] = val / Convert.ToDouble(richTextBox1.Lines.Length);
                    px[p] = Math.Round(px[p], 3);
                    p++;
                }
            }
            progressBar1.Value = 45;
            int num = 0;
            for (int i = 0; i < m.Length; i++)
            {
                if(m[i]>0)
                {
                    num++;
                    richTextBox6.Text += "m[" + num + "]=" + m[i] + "\n";
                }
            }
            num = 0;
            progressBar1.Value = 50;
            for (int i = 0; i < xin.Length; i++)
            {
                if (xin[i] > 0)
                {
                    num++;
                    richTextBox6.Text += "xн[" + num + "]=" + xin[i] + "  хв[" + num + "]=" + xiv[i] + "\n";
                }

            }
            progressBar1.Value = 55;
            double[] fx = new double[m.Length];
            fx[0] = px[0];
            for (int i = 1; i < px.Length; i++)
            {
                if (px[i] != 0)
                {
                    fx[i] = px[i] + fx[i - 1];
                }
            }
            progressBar1.Value = 60;
            double[] zn = new double[m.Length];
            double[] zv = new double[m.Length];
            double[] Fzn = new double[m.Length];
            double[] Fzv = new double[m.Length];
            double[] pi = new double[m.Length];
            double sa;
            sa = SerAr();
            sa = Math.Round(sa, 3);
            double skvt = Skv();
            skvt = Math.Round(skvt, 3);
            for (int i = 0; i < m.Length; i++)
            {
                if (m[i] != 0)
                {
                    zn[i] = (xin[i] - sa) / skvt;
                    if (zn[i] < 0)
                    {
                        zn[i] = zn[i] * (-1);
                    }
                    zv[i] = (xiv[i] - sa) / skvt;
                    if (zv[i] < 0)
                    {
                        zv[i] = zv[i] * (-1);
                    }
                    zn[i] = Math.Round(zn[i], 2);
                    zv[i] = Math.Round(zv[i], 2);
                    for (int j = 0; j < richTextBox3.Lines.Length-1; j++)
                    {
                        String[] temp = richTextBox3.Lines[j].Split('/');
                        if (Math.Abs(zn[i] - Convert.ToDouble(temp[0])) < 0.01)
                        {
                            Fzn[i] = Convert.ToDouble(temp[1]);
                            break;
                        }
                    }
                    for (int j = 0; j < richTextBox3.Lines.Length - 1; j++)
                    {
                        String[] temp = richTextBox3.Lines[j].Split('/');
                        if (Math.Abs(zv[i] - Convert.ToDouble(temp[0])) < 0.01)
                        {
                            Fzv[i] = Convert.ToDouble(temp[1]); 
                            break;
                        }
                    }
                    if((Fzn[i] != 0) && (Fzv[i] != 0))
                    {
                        pi[i] = Fzn[i] - Fzv[i];
                        pi[i] = Math.Round(pi[i], 3);
                    }
                } 
            }
            progressBar1.Value = 70;
            double[] presum = new double[m.Length+1];
            for (int j = 0; j < (m.Length - 1); j++)
            {
                if (pi[j]<0)
                {
                    pi[j] = pi[j] * (-1);
                }
                presum[j] = m[j] - (richTextBox1.Lines.Length * pi[j]);
                presum[j] = Math.Round(presum[j], 3);
            }
            progressBar1.Value = 80;
            num = 0;
            for (int i = 0; i < pi.Length; i++)
            {
                if (pi[i] > 0)
                {
                    num++;
                    richTextBox6.Text += "p[" + num + "]=" + pi[i] + "\n";
                }

            }
            /*for (int j = 0; j < (m.Length); j++)
            {
                if (presum[j] != 0)
                {
                    if ((presum[j + 1] == 0) && (presum[j + 2] == 0) && m[j] < 5)
                    {
                        presum[j - 1] += presum[j];
                        presum[j] = 0;
                        m[j - 1] += m[j];
                        m[j] = 0;
                        pi[j - 1] += pi[j];
                        pi[j] = 0;
                    }
                    if (m[j] < 5)
                    {
                        presum[j + 1] += presum[j];
                        presum[j] = 0;
                        m[j + 1] += m[j];
                        m[j] = 0;
                        pi[j + 1] += pi[j];
                        pi[j] = 0;
                    }
                }
            }*/
            double summa = 0;
            double minpi;
            progressBar1.Value = 85;
            num = 0;
            for (int j = 0; j < (pi.Length - 1); j++)
            {
                if (pi[j] != 0)
                {
                    num++;
                    if(pi[j] < 0 )
                    {
                        pi[j] = pi[j]*(-1);
                    }
                    if(presum[j]<0)
                    {
                        presum[j] = presum[j]*(-1);
                    }
                    minpi = (presum[j]*presum[j])/(richTextBox1.Lines.Length*pi[j]);
                    richTextBox6.Text += "(mi-npi)^2/npi[" + num + "]=" + minpi + "\n";
                    summa += minpi;
                }
            }
            summa = Math.Round(summa, 3);
            richTextBox6.Text += "hi^2=" + summa + "\n";
            try
            {
                using (StreamReader sr = new StreamReader("hi.txt"))
                {
                    String line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        richTextBox4.Text += line + "\n";
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("The file could not be read:");
                MessageBox.Show(e.Message);
            }
            progressBar1.Value = 90;
            int mcount = 0;
            foreach (var d1 in m)
            {
                if(d1 != 0)
                {
                    mcount++;
                }
            }
            string hi;
            hi = richTextBox4.Lines[mcount-3];
            if(summa < Convert.ToDouble(hi))
            {
                label8.Text = "hi^2розр. = " + summa.ToString();
                label9.Text = "<";
                label10.Text = "hi^2табл. = " + hi;
                richTextBox5.Text = "Вибірка відповідає нормальному закону розподілу.";
                ifNormal();
            }
            else
            {
                label8.Text = "hi^2розр. = " + summa.ToString();
                label9.Text = ">";
                label10.Text = "hi^2табл. = " + hi;
                richTextBox5.Text = "Вибірка не відповідає нормальному закону розподілу.";
                ifNotNormal();
            }
            double texskv = Math.Round(Skv(), 3);
            textBox2.Text = Convert.ToString(texskv);
            progressBar1.Value = 100;
            progressBar1.Visible = false;
            return 0;
        }

        public int w()
        {
            progressBar1.Visible = true;
            label13.Text = "Коефіцієнт а";
            label14.Text = "W";
            double skv=0, ser = SerAr();
            ser = Math.Round(ser, 3);
            double[] presum = new double[richTextBox1.Lines.Length];
            progressBar1.Value = 10;
            for (int i = 0; i < (richTextBox1.Lines.Length); i++)
            {
                presum[i] = Convert.ToDouble(richTextBox1.Lines[i]) - ser;
                presum[i] = Math.Round(presum[i], 3);
            }
            foreach (var d in presum)
            {
                skv += d*d;
            }
            progressBar1.Value = 32;
            skv = Math.Round(skv, 3);
            textBox2.Text = Convert.ToString(skv);
            string fileName = richTextBox1.Lines.Length.ToString() + ".txt";
            try
            {
                using (StreamReader sr = new StreamReader("kof/" + fileName))
                {
                    String line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        richTextBox4.Text += line + "\n";
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("The file could not be read:");
                MessageBox.Show(e.Message);
            }
            progressBar1.Value = 41;
            int k=richTextBox4.Lines.Length-1, n=richTextBox1.Lines.Length-1;
            double[] spresum = new double[k];
            for (int i = 0; i < k; i++)
            {
                richTextBox6.Text += "a["+(i+1).ToString()+"]="+richTextBox4.Lines[i]+"  *  ";
                double temp = (Convert.ToDouble(richTextBox1.Lines[n + 1 - (i + 1)]) -
                               Convert.ToDouble(richTextBox1.Lines[i]));
                temp = Math.Round(temp, 3);
                richTextBox6.Text += "x[" + ((n + 1 - (i + 1))+1) + "]-x["+(i+1)+"]=" + temp + "\n";
                spresum[i] = Convert.ToDouble(richTextBox4.Lines[i]) * temp;
                spresum[i] = Math.Round(spresum[i], 3);
            }
            progressBar1.Value = 45;
            double ssum = 0;
            foreach (var d in spresum)
            {
                ssum += d;
            }
            progressBar1.Value = 50;
            ssum = Math.Round(ssum, 3);
            richTextBox6.Text += "S=" + ssum + "\n";
            progressBar1.Value = 55;
            ssum = ssum*ssum;
            ssum = Math.Round(ssum, 3);
            double w = ssum/skv;
            w = Math.Round(w, 3);
            richTextBox6.Text += "W=" + w;
            progressBar1.Value = 60;
            try
            {
                using (StreamReader sr = new StreamReader("w.txt"))
                {
                    String line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        richTextBox3.Text += line + "\n";
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("The file could not be read:");
                MessageBox.Show(e.Message);
            }
            progressBar1.Value = 70;
            double wt = Convert.ToDouble(richTextBox3.Lines[n + 1]);
            if (w < Convert.ToDouble(wt))
            {
                label8.Text = "Wрозр. = " + w.ToString();
                label9.Text = "<";
                label10.Text = "Wтабл. = " + wt.ToString();
                richTextBox5.Text = "Вибірка не відповідає нормальному закону розподілу.";
                progressBar1.Value = 90;
                ifNotNormal();
                progressBar1.Value = 100;
            }
            else
            {
                label8.Text = "Wрозр. = " + w.ToString();
                label9.Text = ">";
                label10.Text = "Wтабл. = " + wt.ToString();
                richTextBox5.Text = "Результати спостереження описуються нормальним законом розподілу.";
                progressBar1.Value = 90;
                ifNormal();
                progressBar1.Value = 100;
            }
            progressBar1.Value = 0;
            progressBar1.Visible = false;
            return 0;
        }

        private void Button1Click(object sender, EventArgs e)
        {
            richTextBox2.Clear();
            richTextBox3.Clear();
            richTextBox4.Clear();
            richTextBox5.Clear();
            richTextBox6.Clear();
            richTextBox7.Clear();
            remove();
            if (richTextBox1.Lines.Length == 0)
            {
                MessageBox.Show("Завантажте з файлу або введіть в ручну вибірку.",
                     "Увага!");
                return;
            }
            if (richTextBox1.Lines.Length<50)
            {
                w();
            }
            else
            {
                pirson();
            }
            textBox1.Text = Convert.ToString(Math.Round(SerAr(),3));
            this.Saved = false;
        }

        private void button2_Click(object sender, EventArgs e)
        {

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                richTextBox1.Clear();
                richTextBox2.Clear();
                richTextBox3.Clear();
                richTextBox4.Clear();
                richTextBox5.Clear();
                richTextBox6.Clear();
                richTextBox7.Clear();
                System.IO.StreamReader sr = new
                   StreamReader(openFileDialog1.FileName);
                richTextBox1.Text = sr.ReadToEnd();
                sr.Close();
            }

            
        }


        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            Button1Click(sender,e);
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {

        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (richTextBox1.Lines.Length == 0)
            {
                MessageBox.Show("Ви не ввели вибірку.", "Error");
                return;
            }
            if (richTextBox7.Lines.Length == 0)
            {
                MessageBox.Show("Немає результату обчислень.", "Error");
                return;
            }
            saveFileDialog1.DefaultExt = "txt";
            List<string> lines = new List<string>();
            lines.Add("Фізична величина: " + textBox3.Text);
            lines.Add("Пункт вимірювання: " + textBox4.Text);
            lines.Add("Місце проведення вимірювання: " + textBox5.Text);
            lines.Add("Дата: " + textBox6.Text);
            lines.Add("Час: " + textBox7.Text);
            lines.Add("Наперед відома похибка: " + textBox8.Text);
            lines.Add("---------------------------------------");
            lines.Add("Вибірка:");
            foreach (var line in richTextBox1.Lines)
            {
                lines.Add(line);
            }
            if (richTextBox2.Lines.Length != 0)
            {
                lines.Add("Промахи:");
                foreach (var line in richTextBox2.Lines)
                {
                    lines.Add(line);
                }
            }
            lines.Add(label8.Text + label9.Text +label10.Text);
            foreach (var line in richTextBox5.Lines)
            {
                lines.Add(line);
            }
            foreach (var line in richTextBox7.Lines)
            {
                lines.Add(line);
            }
            var dialogResult = saveFileDialog1.ShowDialog();
            if(dialogResult == DialogResult.OK)
            {
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(@saveFileDialog1.FileName))
                {
                    foreach (string line in lines)
                    {
                            file.WriteLine(line);
                    }
                }
                this.Saved = true;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void Form1_FormClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
           
            if (!this.Saved)
            {
                
                if (MessageBox.Show("Do you want to save changes to your text?", "My Application",
                   MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    
                    e.Cancel = true;
                   
                }
            }
        }

        private void progressBar1_Click(object sender, EventArgs e)
        {

        }

        private void button4_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
            richTextBox2.Clear();
            richTextBox3.Clear();
            richTextBox4.Clear();
            richTextBox5.Clear();
            richTextBox6.Clear();
            richTextBox7.Clear();
            textBox1.Clear();
            textBox2.Clear();
            label10.Text = "0";
            label9.Text = "=";
            label8.Text = "0";
            label13.Text = "-";
            label14.Text = "-";
        }

        private void button5_Click(object sender, EventArgs e)
        {
            DialogResult result2 = MessageBox.Show("Some helpful tutoria.\n Soon...\n \n \n Lorem ipsum dolor\n sit amet, consectetur adipiscing elit.\n Vivamus in sem justo,\n at cursus neque.\n Quisque sagittis\n lobortis imperdiet.\n Suspendisse potenti.\n Integer faucibus imperdiet mauris,\n tempor interdum elit euismod at.\n Integer nec mattis mauris.\n Sed commodo\n molestie laoreet.",
            "FAQ",
            MessageBoxButtons.OK,
            MessageBoxIcon.Question);
        }
    }
}
